#include "path_filter.h"
#include <windows.h>
#include "log.h"
#include "string_util.h"
#include "win_util.h"

PathFilter::PathFilter(const std::vector<std::wstring> &pathList)
{
    this->trustedPathList = pathList;
    Init();
}

bool PathFilter::Handle(const ProcessInfo &process)
{
    std::wstring fullPath = process.fileName;
    for (auto &item : trustedPathList) {
        if (FindIgnoreCase(fullPath, item)) {
            LOG_DEBUG("process path is trusted.");
            return true;
        }
    }
    for (auto &item : installedPathList) {
        if (FindIgnoreCase(fullPath, item)) {
            LOG_DEBUG("process path is trusted.");
            return true;
        }
    }
    LOG_DEBUG("process {} is untrusted.", UnicodeToUtf8(process.fileName));
    return false;
}

void PathFilter::Update()
{
    std::lock_guard lock(updateLock);
    LOG_INFO("update install path list");
    this->installedPathList.clear();
    for (auto &item : GetInstalledPathList()) {
        bool flag = false;
        for (auto &path : trustedPathList) {
            if (item.find(path) != std::wstring::npos) {
                LOG_DEBUG("path: {}", UnicodeToUtf8(item));
                flag = true;
                break;
            }
        }
        if (!flag) {
            LOG_DEBUG("add install path: {}", UnicodeToUtf8(item));
            this->installedPathList.push_back(item);
        }
    }
}

void PathFilter::Init()
{
    Update();
}